序列化操作(Gson ObjectMapper)


可以先閱讀
7. 物件的淺複製 深複製

眼睛比較好閱讀的JSON物件我們可以透過

public static Gson getPrettyGsonPretty(){
    return new GsonBuilder().setPrettyPrinting().create();
}

深複製(適用於單一物件)

public static Object cloneObject(Object o) {
        String s = gson.toJson(o);
        return gson.fromJson(s, o.getClass());
    }

深複製(單多物件)

public static Object deserializeFromObjectMapper(String json, Class<?> targetClass, boolean isCollection) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        if (isCollection) {
            JavaType clazzType = objectMapper.getTypeFactory().
                    constructCollectionType(List.class, targetClass);
            return objectMapper.readValue(json, clazzType);
        } else {
            return objectMapper.readValue(json, targetClass);
        }
    }
#java #JSON







你可能感興趣的文章

字串小幫手 on linux

字串小幫手 on linux

MTR04_0613

MTR04_0613

Fibonacci sequence

Fibonacci sequence






留言討論